package app

import (
	"bestcore/base"
	"bestcore/common/jwt"
	"bestcore/common/logger"
	"bestcore/common/postgresql"
	"bestcore/common/redis"
	"bestcore/config"
	"fmt"

	"github.com/goccy/go-json"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/recover"
)

var app *fiber.App

type Config struct {
	GlobalConfig     *config.Config
	LoggerConfig     *logger.Config
	RedisConfig      *redis.Config
	PostgresqlConfig *postgresql.Config
	Controllers      []base.BaseController
}

/*
func Init(c *AppConfig) (*fiber.App, error) {
	var err error
	err = config.Init(c.GlobalConfig)
	if err != nil {
		return nil, err
	}
	err = logger.Init(c.LoggerConfig)
	if err != nil {
		return nil, err
	}
	err = redis.Init(c.RedisConfig)
	if err != nil {
		return nil, err
	}
	err = postgresql.Init(c.PostgresqlConfig)
	if err != nil {
		return nil, err
	}
	app = fiber.New()
	fmt.Println("app config load success")
	return app, nil
}
func Get() *fiber.App {
	return app
}
*/

func Run(c *Config) (*fiber.App, error) {
	var err error
	err = config.Init(c.GlobalConfig)
	if err != nil {
		return nil, err
	}
	err = logger.Init(c.LoggerConfig)
	if err != nil {
		return nil, err
	}
	err = redis.Init(c.RedisConfig)
	if err != nil {
		return nil, err
	}
	err = postgresql.Init(c.PostgresqlConfig)
	if err != nil {
		return nil, err
	}
	err = jwt.Init()
	if err != nil {
		return nil, err
	}
	app = fiber.New(fiber.Config{
		JSONEncoder: json.Marshal,
		JSONDecoder: json.Unmarshal,
	})
	app.
		Use(cors.New()).
		Use(recover.New()).
		Use(logger.GetMiddleWare())
	for _, controller := range c.Controllers {
		controller.Install(app)
	}
	/*
		data, _ := json.MarshalIndent(app.Stack(), "", "  ")
		fmt.Println(string(data))
	*/
	app.Listen(fmt.Sprintf(":%d", config.Get().Port))
	return app, nil
}
